package com.tianji.promotion.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.promotion.constants.PromotionConstants;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.domain.query.CodeQuery;
import com.tianji.promotion.domain.utils.CodeUtil;
import com.tianji.promotion.domain.vo.CodePageVO;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.constants.PromotionConstants.COUPON_CODE_MAP_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author Yandel
 * @since 2025-08-15
 */
@Slf4j
@Service
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private BoundValueOperations<String, String> serialOps;

    //方式一

/*    @Override
    @Async("generateExchangeCodeExecutor")
    public void asyncGenerateCode(Coupon coupon) {
        //发放数量
        Integer totalNum = coupon.getTotalNum();
        //1.获取Redis自增序列号
        Long result = serialOps.increment(totalNum);
        if (result == null) {
            return;
        }
        int maxSerialNum = result.intValue();
        List<ExchangeCode> list = new ArrayList<>(totalNum);
        for (int serialNum = maxSerialNum - totalNum + 1; serialNum <= maxSerialNum; serialNum++) {
            // 2.生成兑换码
            String code = CodeUtil.generateCode(serialNum, coupon.getId());
            ExchangeCode e = new ExchangeCode();
            e.setCode(code);
            e.setId(serialNum);
            e.setExchangeTargetId(coupon.getId());
            e.setExpiredTime(coupon.getIssueEndTime());
            list.add(e);
        }
        //3.保存数据库
        saveBatch(list);

        //4.写入Redis缓存，member：couponId，score：兑换码的最大序列号
        stringRedisTemplate.opsForZSet()
                .add(PromotionConstants.COUPON_RANGE_KEY, coupon.getId().toString(), maxSerialNum);
    }*/

    /**
     * 异步生成兑换码
     *
     * @param coupon
     */
    //方式二 异步生成兑换码
    @Override
    @Async("generateExchangeCodeExecutor") //使用generateExchangeCodeExecutor  自定义线程池中的线程异步执行
    public void asyncGenerateCode(Coupon coupon) {
        log.info("开始生成兑换码   线程名为：{}", Thread.currentThread().getName());

        int totalNum = coupon.getTotalNum();//代表券的发放总数量，也就是需要生成的兑换码总数量
        //1.生成自增id借助于redis incrby   键：coupon:code:seriaL        值：100
        Long increment = stringRedisTemplate.opsForValue()
                .increment(PromotionConstants.COUPON_CODE_SERIAL_KEY, totalNum);
        if (increment == null) {
            return;
        }
        int maxSerialNum = increment.intValue();// 本地自增id的最大值
        int begin = maxSerialNum - totalNum + 1;//自增id    循环开始值
        //2.循环生成兑换码调用工具类生成兑换码
        ArrayList<ExchangeCode> list = new ArrayList<>();
        for (int serialNum = begin; serialNum <= maxSerialNum; serialNum++) {
            String code = CodeUtil.generateCode(serialNum, coupon.getId());
            ExchangeCode exchangeCode = new ExchangeCode();
            exchangeCode.setCode(code);
            exchangeCode.setId(serialNum);
            exchangeCode.setExchangeTargetId(coupon.getId());
            exchangeCode.setExpiredTime(coupon.getIssueEndTime());
            list.add(exchangeCode);
        }

        //3.将兑换码信息保存db  exchange_code  批量保存
        this.saveBatch(list);
    }

    @Override
    public PageDTO<CodePageVO> queryExchangeCodeList(CodeQuery query) {
        if (query.getCouponId() == null) {
            throw new BadRequestException("优惠券id不能为空");
        }
        //分页查询
        Page<ExchangeCode> page = this.lambdaQuery()
                .eq(ExchangeCode::getExchangeTargetId, query.getCouponId())
                .eq(ExchangeCode::getStatus, query.getStatus())
                .page(query.toMpPageDefaultSortByCreateTimeDesc());

        List<ExchangeCode> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }
        //po 转 vo
        List<CodePageVO> voList = BeanUtils.copyList(records, CodePageVO.class);
        return PageDTO.of(page, voList);
    }

    @Override
    public Boolean updateExchaingeCodeMark(long serialNum, boolean flag) {
        Boolean boo = stringRedisTemplate.opsForValue().setBit(COUPON_CODE_MAP_KEY, serialNum, flag);
        return boo != null && boo;
    }
}
